package com.example.myproject.repository;

import com.example.myproject.model.ChatMessageEntity;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying; // 导入 Modifying
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional; // 导入 Transactional

import java.util.List;
import java.time.Instant; // 导入Instant
import java.util.Optional; // 导入Optional


@Repository
public interface ChatMessageRepository extends JpaRepository<ChatMessageEntity, Long> {

    // 获取两个用户之间的聊天记录，包括user1发给user2和user2发给user1的
    @Query("SELECT cm FROM ChatMessageEntity cm WHERE (cm.fromUser = ?1 AND cm.toUser = ?2) OR (cm.fromUser = ?3 AND cm.toUser = ?4) ORDER BY cm.timestamp ASC")
    List<ChatMessageEntity> findConversation(String user1, String user2, String user3, String user4);

    // 查询未读消息
    List<ChatMessageEntity> findByToUserAndReadStatus(String toUser, ChatMessageEntity.ReadStatus readStatus);

    // 查询特定对话中特定状态的消息
    List<ChatMessageEntity> findByFromUserAndToUserAndReadStatus(String fromUser, String toUser, ChatMessageEntity.ReadStatus readStatus);

    // 新增方法：根据fromUser, toUser和timestamp查找消息
    Optional<ChatMessageEntity> findByFromUserAndToUserAndTimestamp(String fromUser, String toUser, Instant timestamp);
}